
import { routes, resetRouter } from '@/router'
import { loginAPI } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import axios from "axios";
export default {
  namespaced: true,
  state: {
    routes: routes, // 静态路由的数组
    userInfo: JSON.parse(localStorage.getItem('userInfo')),
    token: getToken(),
    menuList: []
  },
  mutations: {
    setRoutes(state, newRoutes) {
      state.routes = [...newRoutes] // 静态路由 + 动态路由
    },
    // 登陆成功获取
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    setToken(state, token) {
      state.token = token
      // 同步到缓存
      setToken(token)
    },
    removeToken(state, token) {
      state.token = null
      state.userInfo = {} // 清空数据
      localStorage.removeItem('userInfo')
      // 同步到缓存
      removeToken()
    },
    setMenuList(state, filterRoutes) {
      state.menuList = [...filterRoutes]
    },
    // 重置路由
    resetMenu(state) {
      // 重置左侧菜单
      state.menuList = routes
      // 重置路由系统
      resetRouter()
    }

  },
  actions: {
    logout(context) {
      context.commit('removeToken') // 删除token
      context.commit('setUserInfo', {}) // 设置用户信息为空对象
      resetRouter()
      context.commit('resetMenu')
    },
    // context上下文，传入参数
    async login(context, data) {
      // console.log(data)
      // todo: 调用登录接口
      const res = await loginAPI(data)
      // console.log(res.token, 'res')
      // 返回一个token 123456
      context.commit('setUserInfo', {
        id: res.id,
        name: res.name,
        token: res.token,
        userName: res.userName,
        whetherItIsAdmin: res.whetherItIsAdmin
      })
      context.commit('setToken', res.token)
    }
  }
}
